<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :initForm="initForm"
        :getList="getList"
        uniqueId="mesDefectiveReviewTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
    </ele-form-drawer>
    <ele-form-drawer
      v-loading="isLoadingsub"
      class="dialog-pack"
      :isLoading="isLoadingsub"
      v-model="formDataDialog1"
      v-bind="formDescDialog1"
      :request-fn="handleSubmit1"
      :visible.sync="visible1"
      :title="title"
      size="60%"
    >
      <template v-slot:table="{ desc, data, field, formData }"
        ><div>
          <el-table
            :data="formDataDialog1.commentList"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="commentName"
              :label="$t('mesDefectiveReview.reviewDepartment')"
              min-width="90"
            >
            </el-table-column>
            <el-table-column
              prop="commentOpinion"
              :label="$t('mesDefectiveReview.auditOpinion')"
              width="240"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.commentOpinion"
                  :disabled="
                    !scope.row.show || formDataDialog1.reviewStatus == 2
                  "
                  type="textarea"
                  :placeholder="
                    (scope.row.show && formDataDialog1.reviewStatus != 2
                      ? `${$i18n.t('common.input')} `
                      : '') +
                    scope.row.commentName +
                    ' ' +
                    $i18n.t('mesDefectiveReview.auditOpinion')
                  "
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="commentByName"
              :label="$t('mesDefectiveReview.signature')"
            >
            </el-table-column>
            <el-table-column
              prop="commentTime"
              min-width="120"
              :label="$t('mesDefectiveReview.date')"
            >
            </el-table-column>
            <el-table-column
              prop="address"
              :label="$i18n.t('common.operation')"
              width="120"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.show && formDataDialog1.reviewStatus != 2"
                  @click.native.prevent="sumInput(scope.row)"
                  size="small"
                  type="success"
                >
                  {{ $t("ele-form.submitBtnText") }}
                </el-button>

                <el-button v-else disabled type="text">{{
                  $t("mesDefectiveReview.notOperable")
                }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </ele-form-drawer>

    <!-- 导入弹框 -->
    <ele-form-drawer
      size="30%"
      :isLoading="isLoadingImport"
      v-model="importData"
      v-bind="importFormDescDialog"
      :request-fn="handleSubmitImport"
      :visible.sync="importVisible"
      :destroyOnClose="true"
      :title="$i18n.t('mesDefectiveReview.importUsers')"
    >
      <template v-slot:file="{ desc, data, field, formData }">
        <!-- 插槽内容有el-form-item组件包裹 -->
        <uploadNoAuto @onchange="upLoadHandleChange" ref="uploadNoAuto" />
      </template>
    </ele-form-drawer>
  </div>
</template>

<script>
import {
  operateList,
  searchConfig,
  importFormDescDialog,
  formDescDialog,
  rowConfig,
} from "./config";
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  rowDetail,
  importData,
  getReviewStatusList,
  getReviewResultList,
  getDefectLevelList,
  mesDefectiveReviewInfo,
  exportUrl,
} from "@/api/review/mesDefectiveReview";
import uploadNoAuto from "@/components/upload-no-auto";
import { getDict } from "@/api/common";
import { uniqueKey } from "@/utils/judge.js";
import { form } from "./form.js";
export default {
  name: "mesDefectiveReview",
  components: {
    uploadNoAuto,
  },

  mixins: [form],
  data() {
    return {
      title: null,
      initForm: {},
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      formDescDialog, //新增修改框
      searchConfig,
      operateList,
      getList,
      isLoadingImport: false, // 导入数据loading
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          fixed: "left",
          width: 60,
        },
        {
          prop: "reviewCode",
          label: $i18n.t("mesDefectiveReview.reviewCode"),
          width: 150,
          showOverflowTooltip: true,
          fixed: "left",
        },
        {
          prop: "orderCode",
          label: $i18n.t("mesDefectiveReview.workOrderCode"),
          minWidth: 220,
          showOverflowTooltip: true,
          fixed: "left",
        },
        {
          prop: "planCode",
          label: $i18n.t("mesDefectiveReview.prodPlanCode"),
          minWidth: 180,
          showOverflowTooltip: true,
        },

        {
          prop: "workshopCode",
          label: $i18n.t("common.workshopCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "workshopName",
          label: $i18n.t("common.workshopName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "lineCode",
          label: $i18n.t("common.lineCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "lineName",
          label: $i18n.t("common.lineName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "processCode",
          label: $i18n.t("common.processCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "processName",
          label: $i18n.t("common.processName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "equipmentCode",
          label: $i18n.t("mesDefectiveReview.equipmentCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "equipmentName",
          label: $i18n.t("mesDefectiveReview.equipmentName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "prodCode",
          label: $i18n.t("mesDefectiveReview.prodCode"),
          minWidth: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesDefectiveReview.prodName"),
          minWidth: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "seriesCode",
          label: $i18n.t("mesDefectiveReview.seriesCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "seriesName",
          label: $i18n.t("mesDefectiveReview.seriesName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "faultCode",
          label: $i18n.t("mesDefectiveReview.faultCode"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "faultName",
          label: $i18n.t("mesDefectiveReview.faultName"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "rejectQuantity",
          label: $i18n.t("mesDefectiveReview.rejectQuantity"),
          minWidth: 160,
          showOverflowTooltip: true,
        },
        // {
        //   prop: "rejectRatio",
        //   label: $i18n.t("mesDefectiveReview.rejectRatio"),
        //   minWidth: 140,
        //   showOverflowTooltip: true
        // },
        {
          prop: "defectLevel",
          label: $i18n.t("mesDefectiveReview.defectLevel"),
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getDefectLevelList();
            return list.data.result;
          },
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "description",
          label: $i18n.t("mesDefectiveReview.description"),
          minWidth: 260,
          showOverflowTooltip: true,
        },

        {
          prop: "reviewByName",
          label: $i18n.t("mesDefectiveReview.reviewByName"),
          minWidth: 160,
          showOverflowTooltip: true,
        },
        {
          prop: "reviewTime",
          label: $i18n.t("mesDefectiveReview.reviewTime"),
          width: 180,
        },
        {
          prop: "reviewOpinion",
          label: $i18n.t("mesDefectiveReview.reviewOpinion"),
          minWidth: 230,
          showOverflowTooltip: true,
        },
        {
          prop: "createByName",
          label: $i18n.t("common.createByName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          width: 180,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: 180,
        },
        {
          prop: "reviewStatus",
          label: $i18n.t("mesDefectiveReview.reviewStatus"),
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getReviewStatusList();
            return list.data.result;
          },
          fixed: "right",
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "reviewResult",
          label: $i18n.t("mesDefectiveReview.reviewResult"),
          fixed: "right",
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getReviewResultList();
            return list.data.result;
          },
          minWidth: 130,
          showOverflowTooltip: true,
        },

        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 160,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              />
            );
          },
        },
      ],
    };
  },
  computed: {},
  methods: {
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const fnc = {
        add: () => {
          this.disableFields(false);
          this.formDataDialog = {};
          this.visible = true;
        },
        deleteBatch: () => {
          this.$confirm(
            $i18n.t("common.deleteBatch", {
              name: $i18n.t("mesDefectiveReview.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = data.rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },

        addSpecialFinal: () => {
          this.formDescDialog1.isShowSubmitBtn = true;

          this.formDescDialog1.isShowSubmitBtn =
            data.rows[0].reviewStatus == 2 ? false : true;
          this.commentType(data);
          //  this.formDataDialog1.commentList = console.log(data, 1212);
        },
        addSpecial: () => {
          this.formDescDialog1.isShowSubmitBtn = false;
          this.commentType(data);
          //  this.formDataDialog1.commentList = console.log(data, 1212);
        },
        import: () => {
          this.importDialogData = {};
          this.importVisible = true;
        },
      };
      fnc[data.handleName]();
    },

    async commentType(data) {
      let res = await mesDefectiveReviewInfo(data.rows[0].id);
      this.formDataDialog1 = res.data.result;
      this.visible1 = true;

      let resList = res.data.result.commentList.map((ite) => {
        return {
          ...ite,
          show: data.code == ite.commentType,
          commentName: this.formDataDialogType.find(
            (item) => item.commentType == ite.commentType
          ).commentName,
        };
      });
      let listCount = uniqueKey(
        [...resList, ...this.formDataDialogType],
        "commentType"
      );
      this.formDataDialog1.commentList = listCount.map((ite) => {
        return {
          ...ite,
          show: data.code == ite.commentType,
        };
      });

      // 字符串转数组chek
      // this.formDataDialog1.defectLevel =
      //   res.data.result?.defectLevel ?? "" == ""
      //     ? []
      //     : res.data.result.defectLevel.split(",");
    },

    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          this.disableFields(false);
          this.rowDetail(row.id);
          this.visible = true;
        },
        detail: () => {
          this.disableFields(true);
          this.rowDetail(row.id);
          this.visible = true;
        },
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteSingle", {
              name: $i18n.t("mesDefectiveReview.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.rowDel(row.id);
          });
        },
      };
      fnc[handleName]();
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true;
      api(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || title);
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      delete data.userDefined1; // 删除不需要修改的非主键字段
      delete data.userDefined2; // 删除不需要修改的非主键字段
      delete data.userDefined3; // 删除不需要修改的非主键字段
      delete data.userDefined4; // 删除不需要修改的非主键字段
      delete data.userDefined5; // 删除不需要修改的非主键字段
      delete data.userDefined6; // 删除不需要修改的非主键字段
      delete data.userDefined7; // 删除不需要修改的非主键字段
      delete data.userDefined8; // 删除不需要修改的非主键字段
      delete data.userDefined9; // 删除不需要修改的非主键字段
      delete data.userDefined10; // 删除不需要修改的非主键字段
      delete data.createBy; // 删除不需要修改的非主键字段
      delete data.createByName; // 删除不需要修改的非主键字段
      delete data.createTime; // 删除不需要修改的非主键字段
      delete data.updateBy; // 删除不需要修改的非主键字段
      delete data.updateByName; // 删除不需要修改的非主键字段
      delete data.updateTime; // 删除不需要修改的非主键字段
      delete data.activeFlag; // 删除不需要修改的非主键字段
      const params = this.formDataDialog.id
        ? { title: $i18n.t("common.editSuccess"), api: rowUpdate, data }
        : { title: $i18n.t("common.addSuccess"), api: rowCreate, data };
      this.doSubmit(params);
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag;
      this.formDescDialog.isShowSubmitBtn = !flag;
    },
    rowDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result;
      });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //数据文件上传
    upLoadHandleChange(file) {
      this.$set(this.importData, "file", file);
    },
    // 提交导入信息
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error($i18n.t("common.uploadMsg"));
        return;
      }
      const formData = new FormData();
      formData.append("file", this.importData.file.get("file"));
      this.isLoadingImport = true;
      importData(formData)
        .then((res) => {
          this.$message.success($i18n.t("common.importSuccess"));
          this.isLoadingImport = false;
          this.importVisible = false;
          this.refresh();
        })
        .catch((error) => {
          console.log("错误", error);
          this.$set(this.importData, "file", null);
        })
        .finally(() => {
          this.isLoadingImport = false;
          this.$refs.uploadNoAuto.clearFiles();
        });
    },
  },

  async created() {
    const lange = this.$store.getters.language;
    let query = this.$route.query;

    this.initForm = { ...this.initForm, ...query };
    this.operateList = [
      {
        name: $i18n.t("common.export"),
        type: "primary",
        icon: "el-icon-download",
        handleName: "export", //点击时返回的标识
        url: exportUrl,
        //auth: "auth:operlog:export", //权限字段
      },
    ];

    let res = await getDict("mes_comment_type");
    // 表单中标准
    this.formDataDialogType = res.data.result.map((ite) => {
      delete ite.id;
      return {
        ...ite,
        commentType: ite.value,
        commentOpinion: "",
        commentName: ite.description,
        show: false,
      };
    });
    res.data.result.map((ite) => {
      this.operateList.push({
        name:
          lange == "en"
            ? ite.value &&
              ite.value.slice(0, 1).toUpperCase() + ite.value.slice(1)
            : ite.description,
        code: ite.value,
        type: "primary",
        icon: "el-icon-discover",
        handleName: "addSpecial", //点击时返回的标识
        isMultiple: true, //至少选择一条
        //是否可点击；
        disabled: (data) => {
          return data.length != 1;
        },
      });
    });

    this.operateList.push({
      name: $i18n.t("mesDefectiveReview.finalAudit"),
      type: "warning",
      icon: "el-icon-s-check",
      handleName: "addSpecialFinal", //点击时返回的标识
      isMultiple: true, //至少选择一条
      //是否可点击；
      disabled: (data) => {
        return data.length != 1;
      },
    });
  },
};
</script>
